<?php

namespace App\Service\OpenShop\Feishu;


use App\Console\Commands\Fee\InitFeeDate;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\SignSiteMissionEvent;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Http\Resources\OpenShop\StartBusiness\StartBusinessResource;
use App\Library\FeiShu\SendFs;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteLocationReplayModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use App\Remote\Orm\OrmShopRemote;
use App\Service\BaseService;
use App\Service\OpenShop\Feishu\Board\BoardParam;
use App\Service\OpenShop\Feishu\Board\BoardService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Rms\ShopService;
use App\Support\ChangeSupport;
use App\Support\CustomForm\AttributeOpenShopSupport;
use App\Support\CustomForm\AttributeSupport;
use App\Support\CustomForm\ValidateSupport;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * @author Green Leaf <786407418@qq.com>
 */
class StartBusinessService extends BaseService
{
    public static function submitPart(object $rmsUser, object $params, object $attach)
    {
        try {
            DB::beginTransaction();

            $startBusinessParam = (array)$params;

            $startBusiness = OpenShopStartBusinessModel::query()
                                                        ->where("orderNo", $params->orderNo)
                                                        ->first();
            if (!$startBusiness->createdByUid) {
                $startBusinessParam = array_merge([
                    "createdAt"    => time(),
                    "createdByUid" => $rmsUser->id
                ], $startBusinessParam);
            }

            if ($startBusiness) {
                OpenShopStartBusinessModel::query()
                                          ->where("orderNo", $params->orderNo)
                                          ->update($startBusinessParam);
            }

            // TODO 不要每次插入
            if ((array)$attach) {
                OpenShopUploadFileResourceModel::query()->insert((array)$attach);
            }

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            handleException($e);
        }
    }

    /**
     * @param object $rmsUser
     * @param object $params
     * @param object $attach
     * @throws Exception
     */
    public static function submit(object $rmsUser, object $params, object $attach)
    {
        try {
            DB::beginTransaction();
            $startBusinessTimeModel = OpenShopStartBusinessModel::query()
                                      ->where("orderNo", $params->orderNo)
                                      ->first();
            $startBusinessTimeModel->update(array_merge([
                                          "submitTime"   => time(),
                                          "step"         => MainProcessEnum::START_BUSINESS_SUBMIT,
                                          "createdAt"    => time(),
                                          "createdByUid" => $rmsUser->id
                                      ], (array)$params));

            //todo 附件入库
            if ((array)$attach) {
                OpenShopUploadFileResourceModel::query()->insert((array)$attach);
            }

            //签约订单状态修改
            OpenShopSignOrderModel::query()->where("orderNo", $params->orderNo)
                                  ->update([
                                      "status"       => SignOrderEnum::ORDER_STATUS_COMPLETE,
                                      "updatedAt"    => time(),
                                      "updatedByUid" => $rmsUser->id
                                  ]);

            DB::commit();

            $startBusinessTime = $params->startBusinessTime ?? 0;
            if ($startBusinessTime) {
                ShopService::updateShopFormalUseAt($params->orderNo, $startBusinessTime);
            }

            $manager = $rmsUser->id;
            //获得营运顾问
            $mainProcessQuery = OpenShopMainProcessModel::query()
                ->where('orderNo', $params->orderNo)
                ->with(['orderManagerRel'])
                ->first();

            if ($mainProcessQuery != null && count($mainProcessQuery->orderManagerRel)) {
                foreach ($mainProcessQuery->orderManagerRel as $item) {
                    if ($item->type == OpenShopOrderManagerModel::MANAGER_TYPE_5) {
                        $manager = $item->managerUid;
                    }
                }
            }

            //TODO 任务
            event(new SignSiteMissionEvent(
                $params->orderNo,
                MissionTemplateEnum::STEP_STATUS_18,
                $manager
            ));


            //todo 流程日志写入
            event(new OpenShopProcessEvent(
                $manager,
                OpenShopMainProcessModel::query()->where("orderNo", $params->orderNo)->first()->id,
                MainProcessEnum::MAIN_PROCESS_START_BUSINESS,
                MainProcessEnum::START_BUSINESS_SUBMIT
            ));

            //通过orderNo获得对应的shopCode
            $shopCode = (int)OpenShopSignOrderModel::query()
                ->where('orderNo', $params->orderNo)
                ->value('shopCode');
            OrmShopRemote::updateFlag($shopCode);

            //发送消息通知
            $siteLocation = OpenShopSiteLocationModel::query()
                ->where('orderNo', $params->orderNo)->whereIn('source',
                    [
                        OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                        OpenShopSiteLocationModel::SOURCE_HOUSING
                    ])
                ->first();
            if (null !== $siteLocation && HistoryOrderParam::$importOrderMode == false) {

                // 跳转的curl，web/小程序
                $url = \App\Service\OpenShop\Feishu\BaseService::getOpenBoardUrlV2([
                    'orderNo'   => $params->orderNo,
                    'boardType' => BoardService::BOARD_TYPE_BUSINESS
                ]);

                $manager = $rmsUser->username;
                //获得营运顾问
                $mainProcessQuery = OpenShopMainProcessModel::query()
                    ->where('orderNo', $params->orderNo)
                    ->with(['orderManagerRel'])
                    ->first();

                if ($mainProcessQuery != null && count($mainProcessQuery->orderManagerRel)) {
                    foreach ($mainProcessQuery->orderManagerRel as $item) {
                        if ($item->type == OpenShopOrderManagerModel::MANAGER_TYPE_5) {
                            $manager = $item->managerName;
                        }
                    }
                }

                SendFs::newRobot(SendFs::ROBOT_SITE_LOCATION)
                    ->setTitleContent('有新的开业报告提交完成，请注意', vsprintf("门店所在区域: %s %s门店编号: %s %s任务处理角色: %s %s处理人: %s %s任务处理时间: %s %s",
                        [
                            $siteLocation->cityArea,
                            PHP_EOL,
                            $shopCode,
                            PHP_EOL,
                            "督导",
                            PHP_EOL,
                            $manager,
                            PHP_EOL,
                            formatDate(time()),
                            PHP_EOL
                        ]
                    ))
                    ->setUrl('点击查看', $url)
                    ->send();

                //发送复盘任务
                //获得要发送的人员
                $siteId = OpenShopSiteMissionModel::getLastFinishSiteId($params->orderNo, MissionTemplateEnum::STEP_STATUS_4);
                //获得跳转的curl
                $siteLocationUrl = \App\Service\OpenShop\Feishu\BaseService::getSiteLocationAppletUrl($siteId);
                $shopName        = (new NoticeService($params->orderNo))->getShopName();
                $userIdArr = OpenShopSiteLocationReplayModel::query()
                    ->where('orderNo', $params->orderNo)
                    ->pluck('createdByUid')
                    ->toArray();

                $userInfo        = RmsUserService::getRmsUserInfoByUserIds($userIdArr)['data'] ?? [];
//                $templateJson    = sprintf(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteLocationReplay.json')),
//                    $shopCode . ' ' . $shopName,
//                    '@' . implode('@', array_column($userInfo, 'username')),
//                    $url,
//                    $siteLocationUrl
//                );
                $templateJson    = sprintf(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteLocationOpen.json')),
                    $shopCode . ' ' . $shopName,
                    $siteLocation->cityArea,
                    $startBusinessTimeModel->startBusinessTime ? Carbon::createFromTimestamp($startBusinessTimeModel->startBusinessTime)->toDateString() : Carbon::now()->toDateString(),
                    $url
                );
                foreach (array_column($userInfo, 'feishuUserId') as $feishuId) {
                    MessageSendService::sendMessage($feishuId, 'user_id', json_decode($templateJson, true), 'interactive', UserPermissionAuth::MODULE_OPEN_SHOP);
                }
            }

            // 为空时，强制校正管理费收取日期
//            $main = OpenShopMainProcessModel::query()->where('orderNo', $params->orderNo)->select('shopId', 'startFeeTime')->first();
//            if (!$main->startFeeTime) {
//                $startBusinessTime = (int)OpenShopStartBusinessModel::query()
//                                                                    ->where("orderNo", $params->orderNo)
//                                                                    ->value('startBusinessTime');
//
//                $startFeeTime = InitFeeDate::getStartFeeTime($startBusinessTime, $main->shopId);
//                OpenShopMainProcessModel::updateFee($params->orderNo, $startFeeTime);
//
//                Log::warning("InitFeeDate::getStartFeeTime_force shopId:{$main->shopId}");
//            }

        } catch (Exception $exception) {
            DB::rollBack();
            handleException($exception);
        }
    }

    /**
     * @param object $rmsUser
     * @param object $params
     * @param object $attach
     * @throws Exception|GuzzleException
     */
    public static function update(object $rmsUser, object $params, object $attach)
    {
        try {
            DB::beginTransaction();

            ChangeSupport::getInstance()->singleUpdate(
                new OpenShopStartBusinessModel(),
                function ($query) use ($params) {
                    $query->where("orderNo", $params->orderNo);
                },
                array_merge([
                    "createdAt"    => time(),
                    "createdByUid" => $rmsUser->id
                ], (array)$params),
                "开业报告变更",
                OpenShopStartBusinessModel::getOrderLogTranslate()
            );

            //todo 附件入库
            ChangeSupport::getInstance()->attachBatchUpdate(
                new OpenShopUploadFileResourceModel(),
                function ($query) use ($params) {
                    $query->where("orderNo", $params->orderNo)
                          ->whereIn("position", array_keys(UploadFileResourceEnum::START_BUSINESS_MAP))
                          ->where("isDeleted", 0);
                },
                (array)$attach,
                "附件变更",
                OpenShopUploadFileResourceModel::$orderLogTranslate
            );


            ChangeSupport::getInstance()->batchChangesWriteToOrderLog(
                OpenShopSignOrderModel::query()->where("orderNo", $params->orderNo)->first()->id,
                OpenShopSignOrderLogModel::UPDATE_START_BUSINESS,
                $rmsUser->username,
                $rmsUser->id
            );

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            handleException($exception);
        }
    }

    /**
     * @param string $orderNo
     * @return array|void
     * @throws Exception
     */
    public static function detail(string $orderNo)
    {
        try {
            $startBusiness = OpenShopStartBusinessModel::query()
                                                       ->where("orderNo", $orderNo)
                                                       ->with([
                                                           "attachRel" => function ($query) {
                                                               $query->whereIn("position",
                                                                   array_keys(UploadFileResourceEnum::START_BUSINESS_MAP))
                                                                     ->where("isDeleted", 0);
                                                           }
                                                       ])->first();
            return [
                "detail" => $startBusiness ? StartBusinessResource::collection([$startBusiness])->getIterator()
                                                                  ->current() : null
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    public static function detailInput(string $orderNo)
    {
        $res = [];

        $detail = self::detail($orderNo)['detail'] ?? [];

        $page         = 0;
        $res[$page][] = AttributeOpenShopSupport::getInstance('eatInTotal', AttributeSupport::INPUT_TYPE_NUMBER, '是否堂食')
                                                ->setValue($detail->eatInTotal ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['placeholder', '请输入堂食位数'])
                                                ->setCustomAttribute(['unit', '位'])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('hasRight', AttributeSupport::INPUT_TYPE_RADIO, '有无竞对')
                                                ->setValue($detail->hasRight ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::RIGHT_MAP)
                                                ])
                                                ->build();

        $display = ($detail->hasRight ?? OpenShopStartBusinessModel::HAS_RIGHT_NO) == OpenShopStartBusinessModel::HAS_RIGHT_YES ? true : false;

        $res[$page][] = AttributeOpenShopSupport::getInstance('rightDetail',
            AttributeOpenShopSupport::INPUT_TYPE_TEXTAREA, '')
                                                ->setValue($detail->rightDetail ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(false))
                                                ->setCustomAttribute(['placeholder', '请输入竞对情况'], ['display', $display])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('sellChannel',
            AttributeOpenShopSupport::INPUT_TYPE_SELECT_MULTIPLE, '制售动线')
                                                ->setValue(function () use ($detail) {
                                                    return json_decode($detail->sellChannel ?? "", true);
                                                })
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::SELL_CHANNEL_MAP)
                                                ])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('hasMonitorUint', AttributeSupport::INPUT_TYPE_RADIO,
            '监控是否落地')
                                                ->setValue($detail->hasMonitorUint ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::MONITOR_UNIT_MAP)
                                                ])
                                                ->build();
        $page         = 1;

        $res[$page][] = AttributeOpenShopSupport::getInstance('employmentExperience',
            AttributeSupport::INPUT_TYPE_RADIO, '从业经验')
                                                ->setValue($detail->employmentExperience ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::EMPLOYMENT_EXPERIENCE_MAP)
                                                ])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('managementInput', AttributeSupport::INPUT_TYPE_SELECT,
            '经营投入')
                                                ->setValue($detail->managementInput ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::MANAGEMENT_INPUT_TYPE_MAP)
                                                ])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('degreeCooperation', AttributeSupport::INPUT_TYPE_SELECT,
            '配合程度')
                                                ->setValue($detail->degreeCooperation ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::DEGREE_COOPERATION_TYPE)
                                                ])
                                                ->build();

        $page = 2;

        $res[$page][] = AttributeOpenShopSupport::getInstance('startBusinessTime', AttributeSupport::INPUT_DATE, '开业日期')
                                                ->setValue($detail->startBusinessTime ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->build();


        $res[$page][] = AttributeOpenShopSupport::getInstance('sellPriceType', AttributeSupport::INPUT_TYPE_SELECT,
            '执行售价')
                                                ->setValue($detail->sellPriceType ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::SELL_PRICE_TYPE)
                                                ])
                                                ->build();


        $res[$page][] = AttributeOpenShopSupport::getInstance('menuCategory',
            AttributeOpenShopSupport::INPUT_TYPE_SELECT_MULTIPLE, '菜单品类')
                                                ->setValue(function () use ($detail) {
                                                    return json_decode($detail->menuCategory ?? "", true);
                                                })
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute([
                                                    'options',
                                                    AttributeOpenShopSupport::setSelectOptions(OpenShopStartBusinessModel::MENU_CATEGORY_TYPE)
                                                ])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('staffCount', AttributeSupport::INPUT_TYPE_NUMBER, '员工数')
                                                ->setValue($detail->staffCount ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['placeholder', '请输入'])
                                                ->setCustomAttribute(['unit', '人'])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('monthlyWages', AttributeSupport::INPUT_TYPE_NUMBER,
            '月工资总额')
                                                ->setValue($detail->monthlyWages ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['placeholder', '请输入'])
                                                ->setCustomAttribute(['unit', '元'])
                                                ->setCustomAttribute(['money', true])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('startBusinessActivityDesc',
            AttributeOpenShopSupport::INPUT_TYPE_TEXTAREA,
            '开业活动')
                                                ->setValue($detail->startBusinessActivityDesc ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['placeholder', '请输入'])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('promoteChancePointDesc',
            AttributeOpenShopSupport::INPUT_TYPE_TEXTAREA, '提升机会点')
                                                ->setValue($detail->promoteChancePointDesc ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['placeholder', '请输入'])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('leaveBehindQuestionDesc',
            AttributeOpenShopSupport::INPUT_TYPE_TEXTAREA,
            '目前遗留问题')
                                                ->setValue($detail->leaveBehindQuestionDesc ?? '')
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['placeholder', '请输入'])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('startShopPic',
            AttributeOpenShopSupport::INPUT_TYPE_ALBUM_CHECKBOX, '门店照片')
                                                ->setValue(function () use ($detail) {
                                                    return json_decode($detail->startShopPic ?? "", true);
                                                })
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['desc', '门店照片示例'])
                                                ->setCustomAttribute([
                                                    'descImg',
                                                    picturePath('2c/fc/18e5d75604934974aff5f24e11553414915b5ad01d12a1990d9cac8ffcf0.jpeg')
                                                ])
                                                ->build();

        $res[$page][] = AttributeOpenShopSupport::getInstance('startHotMv', AttributeOpenShopSupport::INPUT_TYPE_VIDEO_RADIO, '门店火爆视频')
                                                ->setValue(function () use ($detail) {
                                                    return json_decode($detail->startHotMv ?? "", true);
                                                })
                                                ->setValidateRules(ValidateSupport::getInstance(true))
                                                ->setCustomAttribute(['desc', '火爆视频示例'])
                                                ->setCustomAttribute([
                                                    'descVideo',
                                                    picturePath('83/dc/5f97c2085b7181f9fdccbb20a11bfe0ccf068ffbc224a609eb4af1eac88e.mp4')
                                                ])
                                                ->build();

        return $res;
    }
}
